<?php

namespace backend\controllers;

use common\models\Types;
use Yii;
use backend\models\search\GoodsSearch;
use backend\models\Goods;
use backend\actions\CreateAction;
use backend\actions\UpdateAction;
use backend\actions\IndexAction;
use backend\actions\DeleteAction;
use backend\actions\SortAction;
use backend\actions\ViewAction;

/**
 * GoodsController implements the CRUD actions for Goods model.
 */
class GoodsController extends \yii\web\Controller
{
    public function actions()
    {
        return [
            'index'      => [
                'class' => IndexAction::className(),
                'data'  => function () {
                    $searchModel  = new GoodsSearch();
                    $dataProvider = $searchModel->search(yii::$app->getRequest()->getQueryParams());

                    return [
                        'dataProvider' => $dataProvider,
                        'searchModel'  => $searchModel,
                    ];

                }
            ],
//            'create' => [
//                'class' => CreateAction::className(),
//                'modelClass' => Goods::className(),
//            ],
            'update'     => [
                'class'      => UpdateAction::className(),
                'modelClass' => Goods::className(),
            ],
            'delete'     => [
                'class'      => DeleteAction::className(),
                'modelClass' => Goods::className(),
            ],
            'sort'       => [
                'class'      => SortAction::className(),
                'modelClass' => Goods::className(),
            ],
            'view-layer' => [
                'class'      => ViewAction::className(),
                'modelClass' => Goods::className(),
            ],
        ];
    }

    public function actionCreate()
    {
        /* @var $model \yii\db\ActiveRecord */
        $model = new Goods();
        $model->setScenario('default');
        if (Yii::$app->getRequest()->getIsPost()) {
            if ($model->load(Yii::$app->getRequest()->post()) && $model->save()) {
                Yii::$app->getSession()->setFlash('success', Yii::t('app', 'Success'));

                return $this->redirect(['index', 'GoodsSearch[type]' => $model->type]);
            } else {
                $errorReasons = $model->getErrors();
                $err          = '';
                foreach ($errorReasons as $errorReason) {
                    $err .= $errorReason[0] . '<br>';
                }
                $err = rtrim($err, '<br>');
                Yii::$app->getSession()->setFlash('error', $err);
            }
        }
        $model->loadDefaultValues();
        $data = [
            'model' => $model,
        ];

        return $this->render('create', $data);
    }


}
